<?php
/**
 *	description:ZMAXWECHAT 消息队列模型
 *  author：min.zhang
 *  Email:zhang19min88@163.com
 *	Url:http://www.zmax99.com
 *  copyright:南宁市程序人软件科技有限责任公司保留所有权利
 *  date:2016-05-02
 *  @license GNU General Public License version 3, or later
 *  checker:min.zhang 
 *  check date:2016-05-26
 */

defined('_JEXEC') or die('Restricted Access');

jimport('joomla.application.component.modeladmin');
jimport('joomla.filesystem.file');
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/wechat/token.php");
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/wechat/media.php");
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/wechat/news.php");
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/wechat/material.php");
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/db.php");

class zmaxwechatModelNewsqueue extends JModelAdmin
{	
	public function getForm( $data = array() , $loadData = true)
	{
		$form = $this->loadForm('com_zmaxwechat.newsqueue' ,'newsqueue' ,array('control' =>' jform' ,'load_data' => $loadData ));
		if(!$form)
		{
			return false;
		}
		return $form;
	}
	
	public function loadFormData()
	{
		$data = $this->getItem();
		$this->preprocessData('com_zmaxwechat.newsqueue', $data);
		return $data;
	}
	
	//得到文章的作者
	protected function  getArticleAuthor($articleId)
	{
		$article =JTable::getInstance("content");
		$article->load($articleId);
		$user = JFactory::getUser();
		$user->load($article->created_by);
		return $user->name;
	}
	
	//得到文章的URL
	protected  function getArticleUrl($articleId)
	{
		require_once(JPATH_ROOT."/components/com_content/helpers/route.php");
		$article =JTable::getInstance("content");
		$article->load($articleId);
		return JUri::root().ContentHelperRoute::getArticleRoute($article->id, $article->catid, $article->language);
	}
	
	public function wechat($ids)
	{
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->SELECT("*")->from("#__zmaxwechat_newsqueue")->where("id IN(".implode(',' ,$ids).")");
		$db->setQuery($query);
		$items = $db->loadObjectList();
		
		$token = new zmaxwechatToken();
		$token = $token->getToken();
		$material = new zmaxwechatMaterial($token->token);		
		$media = new zmaxwechatMedia($token->token);
		
		//准备文章内容
		$news = array();//微信系统中news是数组
		
		//加载Joomla文章的信息
		$article =JTable::getInstance("content");
		
		$imgPattern ='<img.*?src="(.*?)">';
		foreach($items as $item)
		{
			$article->load($item->article_id);	
			$content = $article->introtext.$article->fulltext;
			preg_match_all($imgPattern,$content,$matches);
			$srcValue = $matches[1];
			
			$newSrc = array();
			foreach($srcValue as $src)
			{
				$newSrc[$src] = $media->uploadImage(JPATH_ROOT.DS.$src);
			}
			
			foreach($newSrc as $old=>$new)
			{
				$content = str_replace($old ,$new,$content);		
			}
			
			
			//处理引言图片的问题
			$config = json_decode($item->config);
			
			if($config->thumb_media_id)
			{
				$filePath = $config->thumb_media_id;	
			}else
			{
				$filePath = json_decode($article->images)->image_intro;
			}
			
			$introImg = JPath::clean(JPATH_ROOT.DS.$filePath);
			if(!JFile::exists($introImg)) //如果不存在，那么我们需要使用一个默认的图片了
			{
				$defaultIntroImg = "administrator/components/com_zmaxwechat/images/default_intro_img.png";
				$introImg = JPath::clean(JPATH_ROOT.DS.$defaultIntroImg);			
			}
			
			//这里获得默认的作者 ,默认的content_source_url的值			
			$info = $material->getMediaInfo($introImg);
			
			$new = new stdclass();
			$new->title =   $config->title!=""?$config->title:$article->title;
			$new->thumb_media_id = json_decode($info)->media_id;
			$new->author =  $config->author!=""?$config->author:$this->getArticleAuthor($item->article_id);
			
			$new->digest =  $config->digest!=""?$config->digest:mb_strimwidth(strip_tags($article->introtext),0,40);
			$new->show_cover_pic=$config->show_cover_pic!=""?$config->show_cover_pic:"1";
			$new->content=$content;
			
			$new->content_source_url = $config->content_source_url!=""?$config->content_source_url:$this->getArticleUrl($item->article_id);
			
			$news[]=$new;							
		}
		
		//得到图文管理对象 添加了一个图文素材了		
		$result = $media->addNews($news);
		
		 
		if(isset($result->errcode))
		{
			$this->setError($result->errcode.":".$result->errmsg);
			return false;
		}
		
		$mediaId = $result->media_id; //该图文消息的mediaID
		
		//更新new map表
		$newsMap = new stdclass();
		$newsMap->media_id = $mediaId;
		$newsMap->date = JDate::getInstance()->toSql();
		$newsMap->count = count($ids);
		$newsMap->newsqueue_id = implode(',',$ids);
		
		$db = JFactory::getDBO();
		$db->insertObject("#__zmaxwechat_news_map" ,$newsMap);
		
		
		//更新素材列表
		$item = zmaxwechatDBHelper::checkDuplicate(array("media_id"=>$mediaId),"#__zmaxwechat_news");	
		if($item )
		{
			$item->title = $news[0]->title;
			$item->digest = $news[0]->digest;
			$item->content = json_encode($news);
			$item->update_time = $newsMap->date;
			$item->number = $newsMap->count;
			zmaxwechatDBHelper::updateItem("#__zmaxwechat_news" ,$item ,"id");
		}
		else
		{
			$item = new stdclass();
			$item->media_id= $newsMap->media_id;
			$item->title = $news[0]->title;
			$item->digest = $news[0]->digest;
			$item->content = json_encode($news);
			$item->update_time = $newsMap->date;
			$item->number = $newsMap->count;
			$item->create_time = JDate::getInstance()->toSql();
			zmaxwechatDBHelper::insertItem("#__zmaxwechat_news" ,$item );
		}		
		return true;
		
	}

}